from typing import *
from math import inf


class Solution:

    def connectTwoGroups(self, cost: List[List[int]]) -> int:
        m, n = len(cost), len(cost[0])
        f = [[inf] * (1 << n) for _ in range(m + 1)]
        f[0][0] = 0
        for i in range(m):
            for j in range(1 << n):
                enum = j
                while enum > 0:
                    lb = enum & -enum
                    k = lb.bit_length() - 1
                    f[i + 1][j] = min(
                        min(f[i + 1][j ^ lb], f[i][j ^ lb], f[i][j]) +
                        cost[i][k], f[i + 1][j])
                    enum ^= lb
        return f[m][(1 << n) - 1]


so = Solution()
# print(so.connectTwoGroups(cost=[[15, 96], [36, 2]]))
print(so.connectTwoGroups([[1, 3, 5], [4, 1, 1], [1, 5, 3]]))
# print(so.connectTwoGroups([[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]]))
# x = 6
# print(x.bit_count())
# print(x.bit_length())

# print(inf)
# print(0x3f3f3f3f)